<template>
  <div class="popupSelect-container">
    <el-dialog
      title="选择用户"
      :close-on-click-modal="false"
      :visible.sync="visible"
      class="jsbos-dialog jsbos-dialog_center transfer-dialog"
      lock-scroll
      append-to-body
      width="800px"
      :modal-append-to-body="false"
      @close="onClose"
    >
      <div class="transfer__body">
        <div class="transfer-pane">
          <div class="transfer-pane__tools">
            <el-input
              placeholder="请输入关键词查询"
              v-model="keyword"
              @keyup.enter.native="getData"
              v-debounce-input:500ms="getData"
              clearable
              class="search-input"
            >
              <el-button
                slot="append"
                icon="el-icon-search"
                @click="getData"
              ></el-button>
            </el-input>
          </div>
          <div class="transfer-pane__body">
            <el-tabs
              v-model="activeName"
              class="transfer-pane__body-tab"
              :class="{ 'hasSys-tab': hasSys }"
            >
              <el-tab-pane
                label="常用数据"
                name="common"
                class="have_head_icon"
              >
                <el-tree
                  :data="treeData5"
                  :props="props"
                  :expand-on-click-node="false"
                  check-on-click-node
                  @node-click="handleNodeClick2"
                  class="jsbos-common-el-tree"
                  node-key="id"
                  v-loading="loading"
                >
                  <span class="custom-tree-node" slot-scope="{ node, data }">
                    <img
                      v-if="data.headIcon && data.headIcon != '[]'"
                      class="head_icon"
                      :src="
                        data.headIcon && data.headIcon.substring(0, 4) == 'http'
                          ? data.headIcon
                          : baseApi + '' + data.headIcon
                      "
                      alt=""
                    />
                    <img
                      v-else
                      class="head_icon"
                      :src="
                        data.headIcon && data.headIcon.substring(0, 4) == 'http'
                          ? data.headIcon
                          : baseApi + '/api/file/Image/userAvatar/001.png'
                      "
                      alt=""
                    />
                    <span class="text common_text">
                      <span class="node_name">{{ node.label }}</span
                      ><br />
                      <span class="node_organization"
                        >{{ data.companyName }}/{{ data.organizeName }}</span
                      >
                    </span>
                    <!-- <i
                      class="el-icon-delete common_icon"
                      @click.stop="delCommon(data.id)"
                    ></i> -->
                  </span>
                </el-tree>
              </el-tab-pane>
              <el-tab-pane label="全部数据" name="all">
                <el-tree
                  :data="treeData"
                  :props="props"
                  check-on-click-node
                  @node-click="handleNodeClick"
                  class="jsbos-common-el-tree"
                  node-key="id"
                  v-loading="loading"
                  lazy
                  :load="loadNode"
                >
                  <span class="custom-tree-node" slot-scope="{ node, data }">
                    <i :class="data.icon"></i>
                    <span class="text"
                      >{{ node.label }}
                      <span
                        v-if="data.companyName"
                        style="font-size: 12px; color: #ff9900"
                        >@{{ data.companyName }}</span
                      >
                    </span>
                  </span>
                </el-tree>
              </el-tab-pane>
              <el-tab-pane
                label="当前组织"
                name="department"
                class="have_head_icon"
              >
                <el-tree
                  :data="treeData2"
                  :props="props"
                  :expand-on-click-node="false"
                  check-on-click-node
                  @node-click="handleNodeClick2"
                  class="jsbos-common-el-tree"
                  node-key="id"
                  v-loading="loading"
                >
                  <span class="custom-tree-node" slot-scope="{ node, data }">
                    <img
                      v-if="data.headIcon && data.headIcon != '[]'"
                      class="head_icon"
                      :src="
                        data.headIcon && data.headIcon.substring(0, 4) == 'http'
                          ? data.headIcon
                          : baseApi + '' + data.headIcon
                      "
                      alt=""
                    />
                    <img
                      v-else
                      class="head_icon"
                      :src="
                        data.headIcon && data.headIcon.substring(0, 4) == 'http'
                          ? data.headIcon
                          : baseApi + '/api/file/Image/userAvatar/001.png'
                      "
                      alt=""
                    />
                    <span class="text">
                      <span class="node_name">{{ node.label }}</span
                      ><br />
                      <span class="node_organization"
                        >{{ data.companyName }}/{{ data.organizeName }}</span
                      >
                    </span>
                  </span>
                </el-tree>
              </el-tab-pane>
              <el-tab-pane
                label="我的下属"
                name="subordinates"
                class="have_head_icon"
              >
                <el-tree
                  :data="treeData3"
                  :props="props"
                  :expand-on-click-node="false"
                  check-on-click-node
                  @node-click="handleNodeClick2"
                  class="jsbos-common-el-tree"
                  node-key="id"
                  v-loading="loading"
                >
                  <span class="custom-tree-node" slot-scope="{ node, data }">
                    <img
                      v-if="data.headIcon && data.headIcon != '[]'"
                      class="head_icon"
                      :src="
                        data.headIcon && data.headIcon.substring(0, 4) == 'http'
                          ? data.headIcon
                          : baseApi + '' + data.headIcon
                      "
                      alt=""
                    />
                    <img
                      v-else
                      class="head_icon"
                      :src="
                        data.headIcon && data.headIcon.substring(0, 4) == 'http'
                          ? data.headIcon
                          : baseApi + '/api/file/Image/userAvatar/001.png'
                      "
                      alt=""
                    />
                    <span class="text">
                      <span class="node_name">{{ node.label }}</span
                      ><br />
                      <span class="node_organization"
                        >{{ data.companyName }}/{{ data.organizeName }}</span
                      >
                    </span>
                  </span>
                </el-tree>
              </el-tab-pane>
            </el-tabs>
          </div>
        </div>
        <div class="transfer-pane">
          <div class="transfer-pane__tools">
            <span>已选</span>
            <el-button @click="removeAll" type="text" class="removeAllBtn"
              >清空列表
            </el-button>
          </div>
          <div class="transfer-pane__body shadow right-pane">
            <template>
              <div
                v-for="(item, index) in selectedData"
                :key="index"
                class="selected-item"
              >
                <img
                  v-if="item.headIcon && item.headIcon != '[]'"
                  class="head_icon"
                  :src="
                    item.headIcon && item.headIcon.substring(0, 4) == 'http'
                      ? item.headIcon
                      : baseApi + '' + item.headIcon
                  "
                  alt=""
                />
                <img
                  v-else
                  class="head_icon"
                  :src="
                    item.headIcon && item.headIcon.substring(0, 4) == 'http'
                      ? item.headIcon
                      : baseApi + '/api/file/Image/userAvatar/001.png'
                  "
                  alt=""
                />
                <span class="node_text">
                  <span class="node_name">{{ item.fullName }}</span>
                  <br />
                  <span class="node_organization"
                    >{{ item.companyName }}/{{ item.organizeName }}</span
                  >
                </span>
                <i class="el-icon-delete" @click="removeData(index)"></i>
              </div>
            </template>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="visible = false">{{
          $t("common.cancelButton")
        }}</el-button>
        <el-button type="primary" @click="confirm">{{
          $t("common.confirmButton")
        }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getImUserSelector,
  getOrganization,
  getSubordinates,
  getUserInfoList,
  getCommonList,
  updateCommon,
  deleteCommon,
} from "@/api/permission/user";
import {
  addResizeListener,
  removeResizeListener,
} from "element-ui/src/utils/resize-event";

export default {
  name: "user-select",
  inject: {
    elForm: {
      default: "",
    },
    elFormItem: {
      default: "",
    },
  },
  props: {
    value: {
      type: [String, Array],
      default: "",
    },
    ifActiveName: {
      type: String,
      default: "department",
    },
    placeholder: {
      type: String,
      default: "请选择",
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    multiple: {
      type: Boolean,
      default: false,
    },
    collapseTags: {
      type: Boolean,
      default: false,
    },
    clearable: {
      type: Boolean,
      default: true,
    },
    hasSys: {
      type: Boolean,
      default: false,
    },
    size: String,
  },
  data() {
    return {
      visible: false,
      keyword: "",
      activeName: "",
      nodeId: "",
      innerValue: "",
      loading: false,
      props: {
        children: "children",
        label: "fullName",
        isLeaf: "isLeaf",
      },
      treeData: [],
      treeData2: [],
      treeData3: [],
      treeData4: [
        {
          id: "currentUser",
          fullName: "当前用户",
        },
      ],
      treeData5: [],
      selectedData: [],
      tagsList: [],
      inputHovering: false,
      inputWidth: 0,
      initialInputHeight: 0,
    };
  },
  watch: {
    value(val) {
      this.setDefault();
    },
    selectDisabled() {
      this.$nextTick(() => {
        this.resetInputHeight();
      });
    },
    activeName(val) {
      if (this.activeName != "all") {
        this.keyword = "";
      }
      if (!val) return;
      this.nodeId = "1";
      this.treeData = [];
      this.treeData2 = [];
      this.treeData3 = [];
      this.getData();
    },
  },
  computed: {
    baseApi() {
      return "https://gl.bringspring.com/jsbos-manager";
      return window.config.VUE_APP_BASE_API;
    },
    showClose() {
      let hasValue = this.multiple
        ? Array.isArray(this.value) && this.value.length > 0
        : this.value !== undefined && this.value !== null && this.value !== "";
      let criteria =
        this.clearable &&
        !this.selectDisabled &&
        this.inputHovering &&
        hasValue;
      return criteria;
    },
    currentPlaceholder() {
      if (this.multiple && Array.isArray(this.value) && this.value.length) {
        return "";
      } else {
        return this.placeholder;
      }
    },
    selectDisabled() {
      return this.disabled || (this.elForm || {}).disabled;
    },
    _elFormItemSize() {
      return (this.elFormItem || {}).elFormItemSize;
    },
    selectSize() {
      return this.size || this._elFormItemSize || (this.$ELEMENT || {}).size;
    },
    collapseTagSize() {
      return ["small", "mini"].indexOf(this.selectSize) > -1 ? "mini" : "small";
    },
  },
  created() {
    console.log(this.selectedData, "-----");
    this.setDefault();
  },
  mounted() {
    this.getCommon();
    addResizeListener(this.$el, this.handleResize);

    const reference = this.$refs.reference;
    if (reference && reference.$el) {
      const sizeMap = {
        medium: 36,
        small: 32,
        mini: 28,
      };
      const input = reference.$el.querySelector("input");
      this.initialInputHeight =
        input.getBoundingClientRect().height || sizeMap[this.selectSize];
    }
    if (this.multiple) {
      this.resetInputHeight();
    }
    this.$nextTick(() => {
      if (reference && reference.$el) {
        this.inputWidth = reference.$el.getBoundingClientRect().width;
      }
    });
    this.setDefault();
  },
  beforeDestroy() {
    if (this.$el && this.handleResize)
      removeResizeListener(this.$el, this.handleResize);
  },
  methods: {
    onClose() {
      this.activeName = "";
    },
    openDialog() {
      if (this.selectDisabled) return;
      this.visible = true;
      this.activeName = this.ifActiveName;
      this.keyword = "";
      this.nodeId = "1";
      this.selectedData = [];
      this.setDefault();
    },
    confirm() {
      if (this.multiple) {
        this.innerValue = "";
        this.tagsList = JSON.parse(JSON.stringify(this.selectedData));
        let selectedIds = this.selectedData.map((o) => o.id);
        this.$emit("input", selectedIds);
        this.$emit("change", selectedIds, this.selectedData);
        this.$parent.$emit("el.form.input");
        this.$emit("callbackAddressAuthorize");
      } else {
        if (!this.selectedData.length) {
          this.innerValue = "";
          this.$emit("input", "");
          this.$emit("change", "", {});
          this.$parent.$emit("el.form.input");
          return;
        }
        this.innerValue = this.selectedData[0].fullName;
        let selectedIds = this.selectedData.map((o) => o.id);
        this.$emit("input", selectedIds[0]);
        this.$emit("change", selectedIds[0], this.selectedData[0]);
        this.$parent.$emit("el.form.input");
      }
      this.visible = false;
      let userIds = [];
      this.selectedData.forEach((item) => {
        userIds.push(item.id);
      });
      if (userIds.length > 0) {
        updateCommon({
          userId: userIds,
        }).then((res) => {});
      }
    },
    setDefault() {
      if (!this.value || !this.value.length) {
        this.innerValue = "";
        this.selectedData = [];
        this.tagsList = [];
        return;
      }
      const arr = this.multiple ? this.value : [this.value];
      const hasSysItem = arr.some((o) => o === "currentUser");
      getUserInfoList(arr).then((res) => {
        this.selectedData = res.data.list;
        if (hasSysItem) {
          this.selectedData.push({
            id: "currentUser",
            fullName: "当前用户",
          });
        }
        if (this.multiple) {
          this.innerValue = "";
          this.tagsList = JSON.parse(JSON.stringify(this.selectedData));
        } else {
          this.innerValue = this.selectedData.length
            ? this.selectedData[0].fullName
            : "";
        }
        this.$nextTick(() => {
          if (this.multiple) {
            this.resetInputHeight();
          }
        });
      });
    },
    getData() {
      //关键字进行全局搜索
      if (this.keyword) {
        this.activeName = "all";
      }
      if (this.activeName === "all") {
        this.getAllList();
      } else if (this.activeName === "department") {
        this.loading = true;
        getOrganization({
          keyword: this.keyword,
          organizeId: this.$store.state.user.userInfo.organizeId,
        }).then((res) => {
          this.treeData2 = res.data;
          this.loading = false;
        });
      } else if (this.activeName === "subordinates") {
        this.loading = true;
        getSubordinates(this.keyword).then((res) => {
          this.treeData3 = res.data;
          this.loading = false;
        });
      } else if (this.activeName === "common") {
        this.loading = true;
        getCommonList(this.keyword).then((res) => {
          this.treeData5 = res.data;
          this.loading = false;
        });
      } else {
        this.loading = false;
      }
    },
    getCommon() {
      getCommonList({}).then((res) => {
        if (res.data.length > 0) {
          this.activeName = "common";
        }
      });
    },
    getAllList() {
      this.loading = true;
      if (this.keyword) this.nodeId = "1";
      getImUserSelector(this.nodeId, this.keyword).then((res) => {
        this.treeData = res.data.list;
        this.loading = false;
      });
    },
    loadNode(node, resolve) {
      if (node.level === 0) {
        this.nodeId = "1";
        return resolve(this.treeData);
      }
      this.nodeId = node.data.id;
      getImUserSelector(this.nodeId).then((res) => {
        resolve(res.data.list);
      });
    },
    handleNodeClick(data) {
      if (data.type !== "user") return;
      this.handleNodeClick2(data);
    },
    handleNodeClick2(data) {
      console.log(data);
      const boo = this.selectedData.some((o) => o.id === data.id);
      if (boo) return;
      const item = {
        id: data.id,
        fullName: data.fullName,
        headIcon: data.headIcon ? data.headIcon : "",
        companyName: data.companyName ? data.companyName : "",
        organizeName: data.organizeName ? data.organizeName : "",
      };
      this.multiple
        ? this.selectedData.push(item)
        : (this.selectedData = [item]);
    },
    removeAll() {
      this.selectedData = [];
    },
    removeData(index) {
      this.selectedData.splice(index, 1);
    },
    deleteTag(event, index) {
      this.selectedData.splice(index, 1);
      this.confirm();
      event.stopPropagation();
    },
    handleClearClick(event) {
      this.selectedData = [];
      this.confirm();
      event.stopPropagation();
    },
    // resetInputWidth() {
    //   this.inputWidth = this.$refs.reference.$el.getBoundingClientRect().width;
    // },
    handleResize() {
      // this.resetInputWidth();
      // if (this.multiple) this.resetInputHeight();
    },
    resetInputHeight() {
      if (this.collapseTags) return;
      this.$nextTick(() => {
        if (!this.$refs.reference) return;
        let inputChildNodes = this.$refs.reference.$el.childNodes;
        let input = [].filter.call(
          inputChildNodes,
          (item) => item.tagName === "INPUT"
        )[0];
        const tags = this.$refs.tags;
        const tagsHeight = tags
          ? Math.round(tags.getBoundingClientRect().height)
          : 0;
        const sizeInMap = this.initialInputHeight || 40;
        input.style.height =
          this.selectedData.length === 0
            ? sizeInMap + "px"
            : Math.max(
                tags ? tagsHeight + (tagsHeight > sizeInMap ? 6 : 0) : 0,
                sizeInMap
              ) + "px";
      });
    },
    // delCommon(id) {
    //   deleteCommon(id).then((res) => {
    //     this.getData();
    //   });
    // },
  },
  directives: {
    "debounce-input": {
      inserted(el, binding) {
        let timeout;
        el.addEventListener("input", () => {
          clearTimeout(timeout);
          timeout = setTimeout(() => {
            binding.value();
          }, parseInt(binding.arg) || 300);
        });
      },
    },
  },
};
</script>
<style lang="scss" scoped>
.head_icon {
  width: 40px;
  height: 40px;
  border-radius: 40px;
  margin-right: 10px;
}
.have_head_icon {
  >>> .el-tree-node__content {
    height: 54px !important;
  }
  .custom-tree-node .text {
    line-height: 18px !important;
  }
  .node_name {
    color: #333;
  }
  .node_organization {
    color: #999999;
  }
  // .common_text {
  //   margin-right: 15px;
  // }
  // .common_icon {
  //   margin-right: 10px;
  // }
  // .common_icon:hover {
  //   color: #f66f70;
  // }
}
.selected-item {
  position: relative;
  overflow: hidden;
  display: block !important;
  padding: 6px 12px !important;
  .head_icon {
    float: left;
  }
  .node_text {
    max-width: 75% !important;
    float: left;
    // margin-right: 152px;
    line-height: 20px;
    // overflow: auto !important;
  }
  >>> .el-icon-delete {
    position: absolute;
    right: 14px;
    top: 17px;
  }
  .node_name {
    color: #333;
  }
  .node_organization {
    color: #999999;
  }
}
>>> .el-tabs__item {
  width: 25% !important;
}
.search-input {
  >>> .el-input__validateIcon {
    display: none !important;
  }
}
</style>
